const storeUtil = {}

/**
 * 存储sessionStorage
 */
storeUtil.setStore = (name, content) => {
  if (!name) return
  if (typeof content !== 'string') {
    content = JSON.stringify(content)
  }
  window.sessionStorage.setItem(name, content)
}

/**
 * 获取sessionStorage
 */
storeUtil.getStore = name => {
  if (!name) return
  return window.sessionStorage.getItem(name)
}

/**
 * 删除sessionStorage
 */
storeUtil.removeStore = name => {
  if (!name) return
  window.sessionStorage.removeItem(name)
}

/**
 * 存储localStorage
 */
storeUtil.setLocalStore = (name, content) => {
  if (!name) return
  if (typeof content !== 'string') {
    content = JSON.stringify(content)
  }
  window.localStorage.setItem(name, content)
}

/**
 * 获取localStorage
 */
storeUtil.getLocalStore = name => {
  if (!name) return
  return window.localStorage.getItem(name)
}

/**
 * 删除localStorage
 */
storeUtil.removeLocalStore = name => {
  if (!name) return
  window.localStorage.removeItem(name)
}

/**
 * @Description: 设置有过期时间的storage
 * @author tangyuhui
 * @date 2021/5/5 5:10 下午
*/
storeUtil.setExpireStorage = (name, data, expireDays = 1) => {
  const expire = new Date().getTime() + expireDays * 60 * 60 * 24 * 1000
  const obj = {
    data,
    expire
  }
  localStorage.setItem(name, JSON.stringify(obj))
}

/**
 * @Description: 读取缓存(带过期时间)
 * @author tangyuhui
 * @date 2021/5/5 5:10 下午
*/
storeUtil.getExpireStorage = name => {
  const storage = localStorage.getItem(name)
  const time = new Date().getTime()
  let result = null
  if (storage) {
    const obj = JSON.parse(storage)
    // 如果没有过期时间
    if (!obj.expire) {
      result = obj
    } else if (time < obj.expire) {
      result = obj.data
    } else {
      localStorage.removeItem(name)
    }
  }
  return result
}

/**
 * 清空所有本地存储、会话存储
 */
storeUtil.clearAllStore = () => {
  window.localStorage.clear()
  window.sessionStorage.clear()
}

export default storeUtil
